package zz.app.ustbgsmanager.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import zz.app.ustbgsmanager.beans.querycourse.AccessInfo;
import zz.app.ustbgsmanager.beans.querycourse.CourseInfo;
import zz.app.ustbgsmanager.beans.querycourse.CoursesInTerm;
import zz.app.ustbgsmanager.beans.querycourse.Term;
import zz.app.ustbgsmanager.beans.queryscore.Scores;
import zz.app.ustbgsmanager.beans.teachingassessment.CourseAssessment;

/**
 * Created by zz on 2018/5/30 14:19.
 */
public class GSManager {
    public static final String LOGIN_URL = "http://yjsy1.ustb.edu.cn:8080/pyxx/login.aspx";
    public static final String YZM_URL = "http://yjsy1.ustb.edu.cn:8080/pyxx/createyzm.aspx";
    public static final String DEFAULT_URL = "http://yjsy1.ustb.edu.cn:8080/pyxx/default.aspx";
    public static final String LOGOUT_URL = "http://yjsy1.ustb.edu.cn:8080/pyxx/logout.aspx";
    public static final String QUERYSCORE_URL = "http://yjsy1.ustb.edu.cn:8080/pyxx/grgl/xskccjcx.aspx";
    public static final String QUERYCOURSE_URL = "http://yjsy1.ustb.edu.cn:8080/pyxx/pygl/kbcx_xs.aspx";
    public static final String GETXINGMING_URL = "http://yjsy1.ustb.edu.cn:8080/pyxx/leftmenu.aspx";
    public static final String GETTERM_URL = "http://yjsy1.ustb.edu.cn:8080/pyxx/topmenu.aspx";
    public static final String LOGING_URL = "http://yjsy1.ustb.edu.cn:8080/pyxx/loging.aspx";
    public static final String PREFIX_URL = "http://yjsy1.ustb.edu.cn:8080/pyxx/";
    public static final String TEACHINGASSESS_URL = "http://yjsy1.ustb.edu.cn:8080/pyxx/dcpg/jxpjlist.aspx";
    public static final String JXPJLIST_URL="http://yjsy1.ustb.edu.cn:8080/pyxx/dcpg/jxpjlist.aspx?";

    public static final int STATE_WAIT = 0;
    public static final int STATE_CANLOGIN = 1;
    public static final int STATE_CHECKISLOGIN = 2;
    public static final int STATE_WANTLOGOUT = 3;
    public static final int STATE_QUERYSCORE = 4;
    public static final int STATE_QUERYCOURESE = 5;
    public static final int STATE_QUERYCOURSETERM = 6;
    public static final int STATE_GETXINGMING = 7;
    public static final int STATE_GETTERM = 8;
    public static final int STATE_TEACHINGASSESSMENT = 9;

    public static final int INTENT_LOGIN = 1;
    public static final int INTENT_GET_YZM = 2;
    public static final int INTENT_CHECK_ISLOGIN = 3;
    public static final int INTENT_LOGIN_SUCCESS = 4;
    public static final int INTENT_LOGIN_FAILED = 5;
    public static final int INTENT_LOGOUT = 6;
    public static final int INTENT_NO_NETWORK = 7;
    public static final int INTENT_QUERYSCORE = 8;
    public static final int INTENT_NET_FAILED = 9;
    public static final int INTENT_QUERYCOURSE = 10;
    public static final int INTENT_QUERYCOURSETERM = 11;
    public static final int INTENT_GETUSERXINGMING = 12;
    public static final int INTENT_GETTERM = 13;
    public static final int INTENT_TEACHINGASSESSMENT = 14;
    public static final int INTENT_TEACHINGASSESSMENT_COUNT = 15;

    private static final String TAG = "GSManager";

    private static GSManager manager = null;
    private final Context context;
    private int len;
    private byte[] buf = new byte[1024];
    private String queryCourseTermID;
    private String queryCourseViewState;
    private CookieManager cookieManager;
    private Bitmap bmyzm;
    private Handler handler;
    private int managerState = STATE_WAIT;
    private String userxingming;
    private String currentTerm = "";

    public int getTeachingAssessmentsCurrent() {
        return teachingAssessmentsCurrent;
    }

    private int teachingAssessmentsCurrent;

    public int getTeachingAssessmentsTotalCnt() {
        return teachingAssessmentsTotalCnt;
    }

    private int teachingAssessmentsTotalCnt;

    public String getCurrentTerm() {
        return currentTerm;
    }

    public CookieManager getCookieManager() {
        return cookieManager;
    }

    private Thread queryCourseThread;
    private Thread teachingAssessmentThread;

    public ArrayList<CourseAssessment> getTeachingAssessments() {
        return teachingAssessments;
    }

    private ArrayList<CourseAssessment> teachingAssessments;

    private GSManager(Context context) throws IOException {
        this.context = context;
        cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
        CookieHandler.setDefault(cookieManager);

    }


    public static GSManager getInstance(Context context) throws Exception {
        if (manager == null) {
            manager = new GSManager(context);
        }
        return manager;
    }

    public Bitmap getBmyzm() {
        return bmyzm;
    }

    public void setManagerState(int managerState) {
        this.managerState = managerState;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    public void tryLogin(final String username, final String password, final String pinyin, final String yzm) {
        new Thread(new Runnable() {


            @Override
            public void run() {
                try {
                    URL u = new URL(LOGIN_URL);
                    final HttpURLConnection connection = (HttpURLConnection) u.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setDoOutput(true);
                    OutputStream outputStream = connection.getOutputStream();
                    String key = URLEncoder.encode("__VIEWSTATE", "gb2312");
                    key += "=";
                    key += URLEncoder.encode("dDw1MzgxOztsPF9jdGwwOkltYWdlQnV0dG9uMTtfY3RsMDpJbWFnZUJ1dHRvbjI7Pj4EXRy1aCTTFd2bYF0HVIDhJoWKqQ==", "gb2312");
                    key += "&";
                    key += URLEncoder.encode("_ctl0:txtusername", "gb2312");
                    key += "=";
                    key += URLEncoder.encode(username, "gb2312");
                    key += "&";
                    key += URLEncoder.encode("_ctl0:txtpassword", "gb2312");
                    key += "=";
                    key += URLEncoder.encode(password, "gb2312");
                    key += "&";
                    key += URLEncoder.encode("_ctl0:txtxmpy", "gb2312");
                    key += "=";
                    key += URLEncoder.encode(pinyin, "gb2312");
                    key += "&";
                    key += URLEncoder.encode("_ctl0:txtyzm", "gb2312");
                    key += "=";
                    key += URLEncoder.encode(yzm, "gb2312");
                    key += "&";
                    key += URLEncoder.encode("_ctl0:ImageButton1.x", "gb2312");
                    key += "=0";
                    key += "&";
                    key += URLEncoder.encode("_ctl0:ImageButton1.y", "gb2312");
                    key += "=0";
                    outputStream.write(key.getBytes());
                    connection.connect();
                    CookieStore store = cookieManager.getCookieStore();
                    List<HttpCookie> cookies = store.getCookies();
                    String sessionID = null;
                    for (HttpCookie cookie : cookies) {
                        sessionID = cookie.getValue();
                    }
                    SharedPreferences preferences = context.getSharedPreferences("cookies", Context.MODE_PRIVATE);
                    preferences.edit().putString("ASP.NET_SessionId", sessionID).apply();
                    InputStream inputStream = connection.getInputStream();
                    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    while ((len = inputStream.read(buf, 0, 1024)) > 0) {
                        byteArrayOutputStream.write(buf, 0, len);
                    }
                    inputStream.close();
                    String test = byteArrayOutputStream.toString("gb2312");

                    if (test.contains("北京科技大学")) {
                        handler.obtainMessage(INTENT_LOGIN_SUCCESS).sendToTarget();
                    } else {
                        handler.obtainMessage(INTENT_LOGIN_FAILED).sendToTarget();
                    }
                } catch (IOException e) {
                    handler.obtainMessage(INTENT_NET_FAILED).sendToTarget();
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public Thread getQueryCourseThread() {
        return queryCourseThread;
    }

    public void load(final String url) {
        if (managerState == STATE_CHECKISLOGIN) {
            if (url.equals(DEFAULT_URL)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String html = navigateURL(url);
                            if (html.contains("http://yjsy1.ustb.edu.cn:8080/pyxx/PageTemplate/NsoftPage/styles/web_css.css")) {
                                handler.obtainMessage(INTENT_CHECK_ISLOGIN, false).sendToTarget();
                            } else {
                                handler.obtainMessage(INTENT_CHECK_ISLOGIN, true).sendToTarget();
                            }

                        } catch (IOException e) {
                            handler.obtainMessage(INTENT_NET_FAILED).sendToTarget();
                            e.printStackTrace();
                        }
                    }
                }).start();

            }
        } else if (managerState == STATE_WAIT) {
            if (url.equals(LOGIN_URL)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL u = new URL(YZM_URL);
                            HttpURLConnection connection = (HttpURLConnection) u.openConnection();
                            connection.connect();
                            InputStream inputStream = connection.getInputStream();
                            bmyzm = BitmapFactory.decodeStream(inputStream);
                            handler.obtainMessage(INTENT_GET_YZM).sendToTarget();
                            inputStream.close();
                        } catch (IOException e) {
                            handler.obtainMessage(INTENT_NET_FAILED).sendToTarget();
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } else if (managerState == STATE_WANTLOGOUT) {
            if (url.equals(LOGOUT_URL)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String html = navigateURL(url);
                            if (html.contains("http://yjsy1.ustb.edu.cn:8080/pyxx/PageTemplate/NsoftPage/styles/web_css.css")) {
                                handler.obtainMessage(INTENT_LOGOUT).sendToTarget();
                            }
                        } catch (IOException e) {
                            handler.obtainMessage(INTENT_NET_FAILED).sendToTarget();
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } else if (managerState == STATE_QUERYSCORE) {
            if (url.equals(QUERYSCORE_URL)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String html = navigateURL(url);
                            Scores scores = Scores.getScores(html);
                            handler.obtainMessage(GSManager.INTENT_QUERYSCORE, scores).sendToTarget();

                        } catch (IOException e) {
                            handler.obtainMessage(INTENT_NET_FAILED).sendToTarget();
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } else if (managerState == STATE_QUERYCOURESE) {
            if (url.equals(QUERYCOURSE_URL)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String html = navigateURL(url);
                            AccessInfo info = new AccessInfo();
                            info.setTerms(getTerms(html));
                            info.setViewState(getViewState(html));
                            handler.obtainMessage(GSManager.INTENT_QUERYCOURSE, info).sendToTarget();

                        } catch (IOException e) {
                            handler.obtainMessage(INTENT_NET_FAILED).sendToTarget();
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } else if (managerState == STATE_QUERYCOURSETERM) {
            if (url.equals(QUERYCOURSE_URL)) {
                queryCourseThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String key = URLEncoder.encode("__VIEWSTATE", "gb2312");
                            key += "=";
                            key += URLEncoder.encode(queryCourseViewState, "gb2312");
                            key += "&";
                            key += URLEncoder.encode("drpxq", "gb2312");
                            key += "=";
                            key += URLEncoder.encode(queryCourseTermID, "gb2312");
                            key += "&";
                            key += URLEncoder.encode("btnSearch.x", "gb2312");
                            key += "=";
                            key += URLEncoder.encode("0", "gb2312");
                            key += "&";
                            key += URLEncoder.encode("btnSearch.y", "gb2312");
                            key += "=";
                            key += URLEncoder.encode("0", "gb2312");
                            String html = navigateURL(url, key);
                            CoursesInTerm coursesInTerm = getCourseInTerm(html);
                            handler.obtainMessage(GSManager.INTENT_QUERYCOURSETERM, coursesInTerm).sendToTarget();

                        } catch (IOException e) {
                            if (!(e instanceof InterruptedIOException)) {
                                handler.obtainMessage(GSManager.INTENT_QUERYSCORE, null).sendToTarget();
                                handler.obtainMessage(INTENT_NET_FAILED).sendToTarget();
                            }
                            e.printStackTrace();
                        }
                    }
                });
                queryCourseThread.start();
            }
        } else if (managerState == STATE_GETXINGMING) {
            if (url.equals(GETXINGMING_URL)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String html = navigateURL(url);
                            Document document = Jsoup.parse(html);
                            String[] s = document.getElementsByTag("table").get(0).getElementsByTag("tr").get(1).text().split(":");
                            userxingming = s[1];
                            handler.obtainMessage(GSManager.INTENT_GETUSERXINGMING).sendToTarget();

                        } catch (IOException e) {
                            handler.obtainMessage(GSManager.INTENT_NET_FAILED).sendToTarget();
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } else if (managerState == STATE_GETTERM) {
            if (url.equals(GETTERM_URL)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String html = navigateURL(url);
                            Document document = Jsoup.parse(html);
                            currentTerm = document.getElementsByTag("table").get(0).getElementsByTag("tr").get(1).text();
                            handler.obtainMessage(GSManager.INTENT_GETTERM).sendToTarget();

                        } catch (IOException e) {
                            handler.obtainMessage(GSManager.INTENT_NET_FAILED).sendToTarget();
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } else if (managerState == STATE_TEACHINGASSESSMENT) {
            if (url.equals(TEACHINGASSESS_URL)) {
                teachingAssessmentThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String html = navigateURL(url);
                            Document document = Jsoup.parse(html);
                            Element table = document.getElementsByTag("table").get(4);
                            Elements trs = table.getElementsByTag("tr");
                            teachingAssessments = new ArrayList<>();
                            teachingAssessmentsTotalCnt = trs.size() - 4;
                            teachingAssessmentsCurrent = 0;
                            for (int i = 4; i < trs.size(); i++) {
                                teachingAssessmentsCurrent++;
                                handler.obtainMessage(GSManager.INTENT_TEACHINGASSESSMENT_COUNT).sendToTarget();
                                Element tr = trs.get(i);
                                Elements tds=tr.getElementsByTag("td");
                                String assessed=tds.get(5).text();
                                if(assessed.equals("未参加")){
                                    CourseAssessment assessment=new CourseAssessment();
                                    assessment.setAsessed(false);
                                    assessment.setJsxm(tds.get(4).text());
                                    assessment.setKcmc(tds.get(3).text());
                                    assessment.setPjxq(tds.get(0).text());
                                    assessment.setNumber(tds.get(2).text());
                                    teachingAssessments.add(assessment);
                                }else{
                                    CourseAssessment assessment = new CourseAssessment();
                                    assessment.setAsessed(true);
                                    assessment.setJsxm(tds.get(4).text());
                                    assessment.setKcmc(tds.get(3).text());
                                    assessment.setPjxq(tds.get(0).text());
                                    assessment.setNumber(tds.get(2).text());
                                    String id=tds.get(6).getElementsByTag("a").get(0).attr("id");
                                    String s=id.split("__")[1];
                                    String[] s2=s.split("_");
                                    id=id.split("__")[0]+":_"+s2[0]+":"+s2[1];
                                    String viewState=getViewState(html);
                                    String key="";
                                    key += URLEncoder.encode("__VIEWSTATE", "gb2312");
                                    key += "=";
                                    key += URLEncoder.encode(viewState, "gb2312");
                                    key += "&";
                                    key += URLEncoder.encode("__EVENTTARGET", "gb2312");
                                    key += "=";
                                    key += URLEncoder.encode(id, "gb2312");
                                    key += "&";
                                    key += URLEncoder.encode("__EVENTARGUMENT", "gb2312");
                                    key += "=";
                                    String html1=navigateURLWithoutAutoJump(JXPJLIST_URL,key);
                                    Document document1=Jsoup.parse(html1);
                                    String realAddr=document1.getElementsByTag("a").get(0).attr("href");
                                    String html2=navigateURL(realAddr);
                                    Document document2 = Jsoup.parse(html2);
                                    Element table1 = document2.getElementsByTag("table").get(4);
                                    Elements selects = table1.getElementsByTag("select");
                                    Element pjtext = document2.getElementById("txtpjyj");
                                    for (int j = 0; j < selects.size(); j++) {
                                        Element select = selects.get(j);
                                        assessment.getSelections().add(select.getElementsByAttribute("selected").get(0).val());
                                    }
                                    assessment.setAdvices(pjtext.val());
                                    teachingAssessments.add(assessment);
                                }
                            }
                            handler.obtainMessage(GSManager.INTENT_TEACHINGASSESSMENT).sendToTarget();
                        } catch (IOException e) {
                            if (!(e instanceof InterruptedIOException)) {
                                handler.obtainMessage(GSManager.INTENT_QUERYSCORE, null).sendToTarget();
                                handler.obtainMessage(INTENT_NET_FAILED).sendToTarget();
                            }
                        }
                    }
                });
                teachingAssessmentThread.start();
            }
        }


    }

    private String navigateURL(String url) throws IOException {
        URL u = new URL(url);
        SharedPreferences preferences = context.getSharedPreferences("cookies", Context.MODE_PRIVATE);
        String sessionID = preferences.getString("ASP.NET_SessionId", "");
        HttpURLConnection connection = (HttpURLConnection) u.openConnection();
        connection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + sessionID + ";");
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        InputStream inputStream = connection.getInputStream();
        while ((len = inputStream.read(buf, 0, 1024)) > 0) {
            byteArrayOutputStream.write(buf, 0, len);
        }
        inputStream.close();
        return byteArrayOutputStream.toString("gb2312");
    }
    private String navigateURLWithoutAutoJump(String url) throws IOException {
        URL u = new URL(url);
        SharedPreferences preferences = context.getSharedPreferences("cookies", Context.MODE_PRIVATE);
        String sessionID = preferences.getString("ASP.NET_SessionId", "");
        HttpURLConnection connection = (HttpURLConnection) u.openConnection();
        connection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + sessionID + ";");
        connection.setInstanceFollowRedirects(false);
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        InputStream inputStream = connection.getInputStream();
        while ((len = inputStream.read(buf, 0, 1024)) > 0) {
            byteArrayOutputStream.write(buf, 0, len);
        }
        inputStream.close();
        return byteArrayOutputStream.toString("gb2312");
    }
    private String navigateURLWithoutAutoJump(String url,String post) throws IOException {
        URL u = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) u.openConnection();
        SharedPreferences preferences = context.getSharedPreferences("cookies", Context.MODE_PRIVATE);
        String sessionID = preferences.getString("ASP.NET_SessionId", "");
        connection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + sessionID + ";");
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(post.getBytes());
        connection.connect();
        Log.d(TAG, "navigateURLWithoutAutoJump: connection response code:"+connection.getResponseCode());
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        InputStream inputStream = connection.getInputStream();
        while ((len = inputStream.read(buf, 0, 1024)) > 0) {
            byteArrayOutputStream.write(buf, 0, len);
        }
        inputStream.close();
        return byteArrayOutputStream.toString("gb2312");
    }
    private String navigateURL(String url, String post) throws IOException {
        URL u = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) u.openConnection();
        SharedPreferences preferences = context.getSharedPreferences("cookies", Context.MODE_PRIVATE);
        String sessionID = preferences.getString("ASP.NET_SessionId", "");
        connection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + sessionID + ";");
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(post.getBytes());
        connection.connect();
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        InputStream inputStream = connection.getInputStream();
        while ((len = inputStream.read(buf, 0, 1024)) > 0) {
            byteArrayOutputStream.write(buf, 0, len);
        }
        inputStream.close();
        return byteArrayOutputStream.toString("gb2312");
    }

    private String getViewState(String html) {
        Document document = Jsoup.parse(html);
        Elements element = document.getElementsByAttributeValue("name", "__VIEWSTATE");
        return element.get(0).attr("value");
    }

    private ArrayList<Term> getTerms(String html) {
        ArrayList<Term> terms = new ArrayList<>();
        Document document = Jsoup.parse(html);
        Element select = document.getElementsByTag("select").get(0);
        Elements options = select.getElementsByTag("option");
        for (Element e : options) {
            Term t = new Term();
            t.setName(e.text());
            t.setId(e.attr("value"));
            terms.add(t);
        }
        return terms;
    }

    public void setQueryCourseTermID(String id) {
        this.queryCourseTermID = id;
    }

    public void setQueryCourseViewState(String viewState) {
        this.queryCourseViewState = viewState;
    }

    private CoursesInTerm getCourseInTerm(String html) {
        String text;
        Document document = Jsoup.parseBodyFragment(html);
        Element table = document.getElementsByTag("table").get(7);
        CoursesInTerm coursesInTerm = new CoursesInTerm();
        ArrayList<ArrayList<CourseInfo>> infoss = coursesInTerm.getInfos();
        int[] rowspan = new int[13];
        for (int i = 0; i < 13; i++) {
            Element td = table.getElementsByTag("tr").get(i + 1).getElementsByTag("td").get(0);
            String r = td.attr("rowspan");
            int j = 0;
            if (!r.equals("")) {
                j = Integer.parseInt(r);
                for (int k = i + 1; k < i + j; k++) {
                    rowspan[k]++;
                }
                i += j - 1;
            }
        }
        for (int i = 0; i < 7; i++) {
            ArrayList<CourseInfo> infos = new ArrayList<>();
            for (int j = 0; j < 13; j++) {
                Element tr = table.getElementsByTag("tr").get(j + 1);
                Element td = tr.getElementsByTag("td").get(i + 2 - rowspan[j]);
                text = td.getElementsByTag("font").get(0).html();
                String r = td.attr("rowspan");
                int k = 0;
                if (!r.equals("")) {
                    k = Integer.parseInt(r);
                    for (int l = j + 1; l < j + k; l++) {
                        rowspan[l]++;
                    }
                    j += k - 1;
                }
                if (!text.equals("&nbsp;")) {
                    String[] ss = text.split("<br><br>");
                    for (String s : ss) {
                        CourseInfo info = new CourseInfo();
                        info.setTime((j + 1) / 2);
                        String text1 = Jsoup.parse(s).text();
                        info.setDetail(text1);
                        int index = text1.indexOf("(");
                        String name = text1.substring(0, index).trim();
                        int index2 = text1.indexOf(")");
                        String where = text1.substring(index + 1, index2).trim();
                        int index3 = text1.indexOf(";");
                        String when = text1.substring(index2 + 1, index3).trim();
                        int index4 = text1.indexOf("主讲教师", index3);
                        String who = text1.substring(index4 + 5, text1.length()).trim();
                        info.setName(name);
                        info.setWhen(when);
                        info.setWhere(where);
                        info.setWho(who);
                        infos.add(info);
                        Log.d(TAG, "course: " + text1 + "i = " + i + " j = " + j);
                    }
                }
            }
            infoss.add(i, infos);
        }
        return coursesInTerm;

    }

    public String getUserxingming() {
        return userxingming;
    }

    public Thread getTeachingAssessmentThread() {
        return teachingAssessmentThread;
    }
}
